<style lang="scss">
@import '@/assets/css/variable';
.login{
	background-image: linear-gradient(to bottom, #003792 , #01617a);
	padding: 40px 2.4rem;
	.title{
		font-size: 26px;
		font-weight: bold;
	}
	.cell{
		border-radius: 6px;
		overflow: hidden;
		background-color: #013e6b;
		.mobileIcon{
			width: 44px;
		}
		.sendCodeBtn{
			border-radius: 16px;
		}
	}
	.btnBox{
		
	}
	.van-cell{
		background-color: inherit !important;
		padding-left: 0px !important;
		.van-field__control{
			color: white !important;
			padding-left: 0px !important;
			font-size: 16px !important;
		}
	}
}
</style>

<template>
  <div class="login wrapperContent2 fc-fff">
    <div style="height: 100%;margin-top: 40px;">
		<div class="title line-h-l">
			<div>欢迎登录苍南数字创业</div>
			<div>服务平台</div>
		</div>
		<div class="cell flex align-center" style="margin-top: 50px;">
			<img class="mobileIcon" src="../../assets/img/init/mobile.png" alt="">
			<van-field
			    v-model="username"
			    type="text"
				maxlength="11"
			    placeholder="请输入手机号"
			/>
		</div>
		<div class="cell flex align-center mar-t-15">
			<img class="mobileIcon" src="../../assets/img/init/validCode.png" alt="">
			<van-field
			    v-model="code"
			    type="number"
				maxlength="6"
			    placeholder="验证码"
			>
				<template #button>
					<van-button class="sendCodeBtn" size="small" color="linear-gradient(to left, #F1D331 , #FC9600)" @click="sendCode" :loading="loading4SendCode" :disabled="(downTime>0&&downTime<60)">{{(downTime>0&&downTime<60)?`${downTime}秒后可重发`:'获取验证码'}}</van-button>
				</template>
			</van-field>
		</div>
		<div class="btnBox text-center" style="margin-top: 80px;">
			<img src="../../assets/img/init/login.png" style="width: 223px;" @click="onSubmit()">
		</div>
	</div>
  </div>
</template>
<script>
import {Dialog,Toast} from "vant";
// import axios from "axios";
import { mapGetters, mapActions } from "vuex";
export default {
	name:'login',
  data(){
    return {
		loading4SendCode:false,
      _timeOut:false,
      checkbox : "",
      username : "",
      code : "",
      codeText : "发送验证码",
      isSend : true,
      imgCache : "",
      num : "",
	  downTime:60,
	  t:'',
    }
  },
  created() {
    document.title = "登录";
  },
  computed: {
    ...mapGetters(['openid']),
  },
  mounted() {
	  console.log('dev',process.env)
	  console.log('=======user_agent=======',localStorage.getItem('user_agent'))
	const openid = this.openid
	if (!openid || openid==null ||  openid=='null' || openid == 'undefined' || openid == undefined) {
		if(localStorage.getItem('user_agent')=='wxapp'){
			this.getWeixinConfig();
		}
		if(localStorage.getItem('user_agent')=='h5'){
			console.log('localStorage.getItem(process.env.VUE_APP_TOKEN_NAME)',localStorage.getItem(process.env.VUE_APP_TOKEN_NAME))
			if(localStorage.getItem(process.env.VUE_APP_TOKEN_NAME)){
				console.log('=======if=======')
				this.$router.replace("/index");
			}else{
				console.log('=======else=======')
			}
		}
	}else{
		console.log('scToken',localStorage.getItem(process.env.VUE_APP_TOKEN_NAME))
		if(localStorage.getItem(process.env.VUE_APP_TOKEN_NAME)){
			this.$router.replace("/index");
		}else{
			// 有openid但没token的时候，用openid登录
			this.doLoginByOpenId()
		}
	}
  },
  beforeDestroy() {
    if (this.t) {
      clearInterval(this.t);
    }
  },
  methods: {
	  ...mapActions(['GET_Member']),
	  downEvent() {
		this.downTime--
		this.t = setInterval(()=>{
		  this.downTime--
		  if(this.downTime<=0){
			  this.downTime = 60
			  clearInterval(this.t)
		  }
		},1000)
	  },
    sendCode(){
      if(this.username == ""){
        Dialog({ title:'温馨提示', message: "手机号码不能为空", closeOnClickOverlay:true });
        return false;
      }
	  if(!this.$reg.phone.test(this.username)){
	    Dialog({ title:'温馨提示', message: "手机号格式有误", closeOnClickOverlay:true });
	    return false;
	  }
	  this.loading4SendCode = true
	  Toast.loading({
	    message: '加载中...',
	    forbidClick: true,
	  });
	  this.downEvent()
      this.$request.apiSendCode({mobile:this.username}).then(res=>{
          console.log('res',res)
        if(res.code == 200){
		  this.code = res.data.code
        }
      }).finally(res=>{
		  this.loading4SendCode = false
		  Toast.clear()
	  });
    },
    setCodeText(){
      if(this.num>0){
        this.codeText = this.num + "秒后重新";
      }else{
        this.codeText = "发送验证码";
        this.isSend = true;
        if (this._timeOut) {
          clearInterval(this._timeOut);
        }
      }
    },
    onSubmit() {
      if(this.username == ""){
        Dialog({ title:'温馨提示', message: "手机号码不能为空", closeOnClickOverlay:true });
        return false;
      }
      if(this.code == ""){
        Dialog({ title:'温馨提示', message: "短信验证码不能为空", closeOnClickOverlay:true });
        return false;
      }
      // if(this.checkbox == ""){
      //   Dialog({ title:'温馨提示', message: "需要勾选协议", closeOnClickOverlay:true });
      //   return false;
      // }
	  const params = {
		  mobile:this.username,
		  code:this.code
	  }
      Toast.loading({
		  message: '加载中...',
		  forbidClick: true,
	  });
	  if (process.env.NODE_ENV === 'prod') {
	  	params.open_id = this.openid
	  }
      this.$request.apiLogin(params).then(result => {
        if(result.code == 200){
          let data = result.data;
          localStorage.setItem(process.env.VUE_APP_TOKEN_NAME,data.token);
		  this.GET_Member({})
		  this.toMain()
        }
      }).finally(res=>{
		  Toast.clear()
	  });
    },
	toMain() {
		const redirect = this.$route.query.redirect
		console.log('redirect',redirect)
		localStorage.setItem('fromPage','login')
		this.bus.$emit('fromLogin')
		if(redirect){
		    this.$router.replace(redirect);
		}else{
			this.$router.replace("/index");
		}
	},
	// 登录相关
	getWeixinConfig() {
	  console.log('getWeixinConfig')
	  const _this = this;
	  const url = (location.href.split('#')[0])
	  let params = {
		  url
	  };
	  console.log('params',params)
	  _this.$request.getWeixinConfig(params).then((res) => {
		  console.log('res_getWeixinConfig',res)
		  const appId = res.data.appId
	    _this.$store.commit("setAppid", appId);
	    // _this.getCode(res.data.value.appid)
	    // if (process.env.NODE_ENV == "prod") {
	    //   _this.getCode(appId);
	    // }
		_this.getCode(appId);
	  });
	},
	getCode(appid) {
	  // 非静默授权，第一次有弹框
	  const _this = this;
	  const code = this.getUrlParam("code"); // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
	  const local = window.location.href;
	  if (code == null || code === "") {
	    window.location.href =
	      "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
	      appid +
	      "&redirect_uri=" +
	      encodeURIComponent(local) +
	      "&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect";
	  } else {
	    _this.$store.commit("setCode", code);
	    _this.getOpenId(code); //把code传给后台获取用户信息
	  }
	},
	getUrlParam(name) {
	  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	  var r = window.location.search.substr(1).match(reg);
	  if (r != null) return unescape(r[2]);
	  return null;
	},
	getOpenId(code) {
	  const _this = this;
	  let params = {
	    appid: _this.$store.state.appid,
	    // secret: _this.$store.state.secret,
	    code: code,
	  };
	  console.log("getOpenid",params)
	  _this.$request.getOpenid(params).then((res) => {
		  console.log('getOpenid_res',res)
		  if(res.data.open_id){
			  _this.$store.commit("setOpenid", res.data.open_id);
			  // 调用登录接口 doLoginByOpenId
			  _this.doLoginByOpenId()
		  }
	  });
	},
	doLoginByOpenId() {
		const openid = this.openid
		if (!openid || openid==null ||  openid=='null' || openid == 'undefined' || openid == undefined) {
			location.reload()
			return
		}
		let params = {
		  open_id: this.openid,
		};
		console.log("doLoginByOpenId_params",params)
		this.$request.doLoginByOpenId(params).then((res) => {
			if(res.code == 200) {
				const data = res.data
				localStorage.setItem(process.env.VUE_APP_TOKEN_NAME,data.token);
				this.toMain()
			}
		});
	}
  }
}

</script>